﻿using BCVP.Net8.Common.DB;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Common;

namespace WMS.Extensions
{
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            // 默认添加主数据库连接
            if (!string.IsNullOrEmpty(AppSettings.app("MainDB")))
            {
                MainDb.CurrentDbConnId = AppSettings.app("MainDB");
            }

            // 遍历所有数据库配置
            BaseDBConfig.MutiConnectionString.allDbs.ForEach(m =>
            {
                var config = new ConnectionConfig()
                {
                    ConfigId = m.ConnId.ObjToString().ToLower(),
                    ConnectionString = m.Connection,
                    DbType = (DbType)m.DbType,
                    IsAutoCloseConnection = true,
                    MoreSettings = new ConnMoreSettings()
                    {
                        IsAutoRemoveDataCache = true,
                        SqlServerCodeFirstNvarchar = true,
                    },
                    InitKeyType = InitKeyType.Attribute
                };

                // 直接添加到有效配置，不再区分日志库
                BaseDBConfig.ValidConfig.Add(config);
                BaseDBConfig.AllConfigs.Add(config);
            });

            // 移除日志库配置检查
            // if (BaseDBConfig.LogConfig is null)
            // {
            //     throw new ApplicationException("未配置Log库连接");
            // }

            // 验证至少配置了一个数据库
            if (!BaseDBConfig.AllConfigs.Any())
            {
                throw new ApplicationException("请在配置文件中至少配置一个数据库连接");
            }

            // SqlSugarScope是线程安全，可使用单例注入
            services.AddSingleton<ISqlSugarClient>(o =>
            {
                return new SqlSugarScope(BaseDBConfig.AllConfigs);
            });
        }
    }
}
